package com.lzq.mq.common.remote;

import com.alibaba.fastjson2.JSON;
import com.lzq.mq.common.cache.NameServerSyncFutureManager;
import com.lzq.mq.common.coder.TcpMsg;
import com.lzq.mq.common.dto.BaseNameServerRemoteDTO;
import com.lzq.mq.common.dto.HeartBeatDTO;
import com.lzq.mq.common.dto.PullBrokerIpRespDTO;
import com.lzq.mq.common.dto.ServiceRegistryRespDTO;
import com.lzq.mq.common.enums.NameServerResponseCode;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/*
 处理对nameserver给客户端返回的数据内容
 */
@Slf4j
@ChannelHandler.Sharable
public class NameServerRemoteRespHandler extends SimpleChannelInboundHandler<TcpMsg> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TcpMsg msg) {

        int code = msg.getCode();
        if (NameServerResponseCode.REGISTRY_SERVICE_SUCCESS.getCode() == code) {
            // 注册成功
            parseBodyAndSetFuture(msg, ServiceRegistryRespDTO.class);
        } else if (NameServerResponseCode.ERROR_USER_OR_PASSWORD.getCode() == code) {
            parseBodyAndSetFuture(msg, ServiceRegistryRespDTO.class);
        } else if (NameServerResponseCode.HEART_BEAT_SUCCESS.getCode() == code) {
            parseBodyAndSetFuture(msg, HeartBeatDTO.class);
        } else if (NameServerResponseCode.PULL_BROKER_ADDRESS_SUCCESS.getCode() == code) {
            parseBodyAndSetFuture(msg, PullBrokerIpRespDTO.class);
        }
    }

    /**
     * 解析报文并设置future
     * @param msg 报文
     * @param clazz dto类
     * @return 传递的报文内容 clazz类型
     */
    private <T extends BaseNameServerRemoteDTO> T parseBodyAndSetFuture(TcpMsg msg, Class<T> clazz) {
        T dto = null;

        byte[] body = msg.getBody();

        String str = new String(body);
        try {
            dto = JSON.parseObject(body, clazz);  // 解析返回报文
        } catch (Exception e) {
            // 讲body转化为字符串
            String bodyStr = new String(body);
            log.error("解析报文异常:{}", bodyStr);
        }

        // 设置值并释放future
        SyncFuture syncFuture = null;

        if (dto != null) {
            syncFuture = NameServerSyncFutureManager.get(dto.getMsgId());
        } else {
            log.error("未找到对应的dto:{}", dto);
        }

        if (syncFuture != null) {
            syncFuture.setResponse(msg);
        } else {
            log.error("未找到对应的future:{}", dto);
        }

        return dto;
    }
}
